package controller;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import pojo.Book;
import pojo.BookRelative;
import pojo.Comment;
import pojo.Topic;
import pojo.User;

import java.util.*;

import dao.BookDAO;
import dao.BookRelativeDAO;
import dao.CommentDAO;
import dao.TopicDAO;
import pojo.ListBook;
 
@Controller
public class ChiTietSachController {
 
    @RequestMapping("/ChiTietSach.do")
    public String getsach(
    		@RequestParam(value="bookid", required = false) String bookId,
			Model model,
			HttpServletRequest request
    		) {
    	HttpSession session = request.getSession();
    	String st2= request.getRequestURL().toString();
    	session.setAttribute("oldUrl", st2+"?bookid="+bookId);
    	BookDAO bd= new BookDAO();
    	Book b= bd.getBookByID(Integer.parseInt(bookId));
    	if(b==null) return     ("page/FrontEnd/TrangChu");
    	BookRelativeDAO brdao= new BookRelativeDAO(); 
    	//xu li viec sach lien quan voi nhau
		ListBook  listBook=(ListBook) session.getAttribute("listBook");
    	if(listBook==null)
    	{
    		listBook= new ListBook();
    		List<Book> lbook=new ArrayList<Book>();
    		lbook.add(b);
    		listBook.set(lbook);
    		session.setAttribute("listBook",listBook);
    		
    	}
    	else
    	{
    		List<Book> lbook=listBook.get();
    		
    		for(int i= 0; i< lbook.size();i++)
    		{
    			Book t = lbook.get(i);
    			//brdao.insertOrUpdate(b, t);
    			brdao.insertOrUpdate(t, b);
    		}
    		System.out.print("das");
    		listBook.add(b);
    		session.setAttribute("listBook",listBook);
    	}
    
    	
    	//xu li viec sach lien quan voi nhau
    	List<Book> lBookRelative = brdao.getNBookShouldView(b, 20);
    	int lbrelativeSize=0;
    	if(lBookRelative!=null) 
    		{
    			lbrelativeSize=lBookRelative.size()/4;
    			if(lBookRelative.size()%4!= 0) lbrelativeSize++;
    		}
    
    	model.addAttribute("lsize", lbrelativeSize);
    	model.addAttribute("lbrelative", lBookRelative);
    	int view;
    	if(b.getView()==null)
    		view = 10;
    		else	view= b.getView()+1;
    	b.setView(view);
    	bd.update(b);
    	model.addAttribute("book",b);
    	CommentDAO cd= new CommentDAO();
    	List<Comment> lcomment=cd.getCommentByBook(b);
    	if(lcomment.size()==0) lcomment=null;

    	User user= (User)session.getAttribute("user");
    	model.addAttribute("user",user);
     	model.addAttribute("lcomment",lcomment);
        return ("page/FrontEnd/ChiTietSach");
    }
   

}